
// server/controllers/groupController.js
const fs = require('fs')
const path = require('path')
const { hasDuplicateGroups } = require('../utils/fileUtils')

const BASE_DIR = path.join(__dirname, '../data')

// 删除组数据
exports.deleteGroup = (req, res) => {
  const { folder, file, groupName } = req.params
  const filePath = path.join(BASE_DIR, folder, file)

  if (!fs.existsSync(filePath)) {
    return res.status(404).json({ success: false, message: '文件不存在' })
  }

  try {
    const data = JSON.parse(fs.readFileSync(filePath, 'utf-8'))
    if (!data[groupName]) {
      return res.status(404).json({ success: false, message: '组不存在' })
    }

    delete data[groupName]

    if (Object.keys(data).length === 0) {
      fs.unlinkSync(filePath)
      return res.json({ success: true, message: `组 ${groupName} 已删除，文件已清空并被删除` })
    }

    fs.writeFileSync(filePath, JSON.stringify(data, null, 2), 'utf-8')
    res.json({ success: true, message: `组 ${groupName} 已成功删除` })
  } catch (error) {
    res.status(500).json({ success: false, message: '删除组失败' })
  }
}

// 修改组数据
exports.updateGroup = (req, res) => {
  const { folder, file, groupName } = req.params
  const filePath = path.join(BASE_DIR, folder, file)

  if (!fs.existsSync(filePath)) {
    return res.status(404).json({ success: false, message: '文件不存在' })
  }

  try {
    const data = JSON.parse(fs.readFileSync(filePath, 'utf-8'))
    if (!data[groupName]) {
      return res.status(404).json({ success: false, message: '组不存在' })
    }

    const newGroupData = req.body.newData
    if (!Array.isArray(newGroupData)) {
      return res.status(400).json({ success: false, message: '数据格式错误' })
    }

    const historicalData = Object.entries(data)
      .filter(([key]) => key !== groupName)
      .flatMap(([, value]) => value)

    if (hasDuplicateGroups({ [groupName]: newGroupData }, historicalData)) {
      return res.status(400).json({ success: false, message: '数据包含重复的子数组，编辑失败！' })
    }

    data[groupName] = newGroupData
    fs.writeFileSync(filePath, JSON.stringify(data, null, 2), 'utf-8')
    res.json({ success: true, message: `组 ${groupName} 已成功修改` })
  } catch (error) {
    res.status(500).json({ success: false, message: '修改组失败' })
  }
}
